package com.czy.owner.ui.accountbalance;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.ReChangeAdapter;
import com.czy.owner.alipay.PayResult;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.RechargeEntity;
import com.czy.owner.global.Constants;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.RxBusEvent;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.store.StoreListActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.wxapi.WXPayEntryActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangyang on 2016/10/8 0008.
 * 充值
 */
public class RechargeActivity extends BaseActivity {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.rel_custom_recharge)
    RelativeLayout relCustomRecharge;
    @BindView(R.id.et_jine)
    EditText etJine;
    @BindView(R.id.img_cancle)
    ImageView imgCancle;
    @BindView(R.id.tv_paid_content)
    TextView tvPaidContent;
    @BindView(R.id.cb_zhifubao)
    CheckBox cbZhiFuBao;
    @BindView(R.id.cb_weixin)
    CheckBox cbWeiXin;
    private ReChangeAdapter adapter;
    private List<RechargeEntity> listData = new ArrayList<>();
    private String seletPaidType = "aliPay";
    private static final int SDK_PAY_FLAG = 1;//支付
    private String actual = "0";
    private int storeId;
    private int topUpPlanId = 0;
    private String customSwitch;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        MyLog.e("yang", "resultInfo==" + resultInfo);
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        RxBus.getDefault().post(Constants.RECHARGE_SUCCESS_CODE, new CommonEvent(RxBusEvent.RECHARGE));
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        PhoneUtils.ShowToastMessage(RechargeActivity.this, "支付失败");
                    }
                    break;
                }


            }
        }

    };

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_rechange;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.recharge);
        storeId = getIntent().getIntExtra("storeId", 0);
        customSwitch = getIntent().getStringExtra("customSwitch");
        MyLog.e("yang", "storeId===" + storeId);
        etJine.addTextChangedListener(new EditChangedListener());
        etJine.setSelection(etJine.getText().toString().length());
        RxBus.getDefault().register(this);
        initAdapter();
        getData();


    }

    @Override
    protected void updateViews() {

    }


    class EditChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            actual = etJine.getText().toString().trim();
            if (actual.length() > 0) {
                imgCancle.setVisibility(View.VISIBLE);
            } else {
                imgCancle.setVisibility(View.GONE);
            }

        }
    }


    private void initAdapter() {
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_shopping_strategy_divider_decoration));
        adapter = new ReChangeAdapter(this, listData);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<RechargeEntity>() {
            @Override
            public void onItemClick(int position, RechargeEntity data, View view) {
                MyLog.e("yang","customSwitch=="+customSwitch);
                if(customSwitch.equals("true")){
                    if (position != (adapter.getItemCount() - 1)) {
                        if (adapter.getSelectedPostion() == position) {
                            adapter.setSelectedPostion(-1);
                            relCustomRecharge.setVisibility(View.GONE);
                            etJine.setText("");
                            etJine.clearFocus();
                            topUpPlanId = 0;
                            MyLog.e("yang","aaa");
                        } else {
                            adapter.setSelectedPostion(position);
                            relCustomRecharge.setVisibility(View.GONE);
                            etJine.setText("");
                            etJine.clearFocus();
                            topUpPlanId = data.getTopUpPlanId();
                            MyLog.e("yang","bbb");
                        }
                    } else {
                        adapter.setSelectedPostion(position);
                        relCustomRecharge.setVisibility(View.VISIBLE);
                        etJine.requestFocus();
                        topUpPlanId = 0;
                        MyLog.e("yang","ccc");
                    }

                }else {
                    if (adapter.getSelectedPostion() == position) {
                        adapter.setSelectedPostion(-1);
                        relCustomRecharge.setVisibility(View.GONE);
                        etJine.setText("");
                        etJine.clearFocus();
                        topUpPlanId = 0;
                        MyLog.e("yang","eee");
                    } else {
                        adapter.setSelectedPostion(position);
                        relCustomRecharge.setVisibility(View.GONE);
                        etJine.setText("");
                        etJine.clearFocus();
                        topUpPlanId = data.getTopUpPlanId();
                        MyLog.e("yang","fff");

                    }
                }

                adapter.notifyDataSetChanged();
            }
        });
    }


    private void getData() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_MARKETING_GETTOPUPPLANLIST;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSession(RechargeActivity.this));
        params.addBodyParameter("storeId", storeId + "");
        params.addBodyParameter("number", "5");
        MyLog.e("yang", "params===" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                String data = PhoneUtils.checkResponseFlag(RechargeActivity.this, result);
                if (data != null) {
                    List<RechargeEntity> mData = new Gson().fromJson(data, new TypeToken<List<RechargeEntity>>() {
                    }.getType());
                    if(customSwitch.equals("true")){
                        mData.add(new RechargeEntity(1));
                        adapter.setList(mData);
                        if (mData.size() == 1) {
                            adapter.setSelectedPostion(0);
                            relCustomRecharge.setVisibility(View.VISIBLE);
                            etJine.requestFocus();
                        }
                    }else {
                        adapter.setList(mData);
                    }


                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }


    //支付宝支付
    @OnClick(R.id.cb_zhifubao)
    public void cbZhiFuBaoOnClick(View view) {
        if (cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(false);
            seletPaidType = "aliPay";
        } else {
            seletPaidType = "11";
        }


    }

    //微信支付
    @OnClick(R.id.cb_weixin)
    public void cbWeiXinOnClick(View view) {
        if (cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(false);
            seletPaidType = "wxPay";
        } else {
            seletPaidType = "22";
        }


    }


    //支付宝充值
    private void reChangePaid() {
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_CRETETOPUPORDER;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSession(RechargeActivity.this));
        params.addBodyParameter("storeId", storeId + "");
        if (topUpPlanId != 0) {
            params.addBodyParameter("topUpPlanId", topUpPlanId + "");
        } else {
            params.addBodyParameter("topUpAmount", actual);
        }
        params.addBodyParameter("payTypeName", seletPaidType);
        MyLog.e("yang", "parmas==" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                try {
                    String data = PhoneUtils.checkResponseFlag(RechargeActivity.this, result);
                    if (data != null) {
                        if (seletPaidType.equals("aliPay")) {
                            aliPayPaidStart(data);
                        } else if (seletPaidType.equals("wxPay")) {
                            if (isWXAppInstalledAndSupported()) {
                                WXPayEntryActivity.wxPayPaidStart(RechargeActivity.this, data, RxBusEvent.RECHARGE);
                            } else {
                                PhoneUtils.ShowToastMessage(RechargeActivity.this, getString(R.string.isInstallwx));
                            }
                        }
                    }

                } catch (Exception e) {

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    //判断是否安装微信客户端
    public boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(WXPayEntryActivity.APP_ID);
        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled() && msgApi.isWXAppSupportAPI();
        return sIsWXAppInstalledAndSupported;
    }

    private void aliPayPaidStart(final String data) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(RechargeActivity.this);
                // 调用支付接口，获取支付结果
                Map<String, String> result = alipay.payV2(data, true);
                MyLog.e("yang", "result==" + result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @OnClick(R.id.img_cancle)
    public void imgCleanText(View view) {
        etJine.setText("");
    }

    @OnClick(R.id.btn_sure_paid)
    public void btnSurePaidOnClick(View view) {

        if (topUpPlanId == 0) {
            if (TextUtils.isEmpty(actual)|| actual.equals("0")) {
                PhoneUtils.ShowToastMessage(RechargeActivity.this, "请选择或者输入正确的充值金额");
                return;
            }
        }

        if (TextUtils.isEmpty(actual) || actual.equals("0")) {
            if (topUpPlanId == 0) {
                PhoneUtils.ShowToastMessage(RechargeActivity.this, "请选择或者输入正确的充值金额");
                return;
            }
        }


        reChangePaid();

    }


    @Subscribe(code = Constants.RECHARGE_SUCCESS_CODE, threadMode = ThreadMode.MAIN)
    public void eventRecharge(CommonEvent rechargeEvent) {
        finish();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }
}
